package cn.tedu.knows.portal.security;

import cn.tedu.knows.portal.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
//这个配置类会在SpringBoot启动时被解析
//下面的注解表示启动Spring-Security的权限管理功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig
                    extends WebSecurityConfigurerAdapter {
    //写了这个类之后,application.properties文件中配置的admin作废
    //必须继承WebSecurityConfigurerAdapter父类
    //这个父类中提供了配置Spring-Security各种功能的方法

    //从Spring容器中获得通过查询数据库返回用户详细的对象
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    //如果需要使用代码设置一个用户,需要重新下面的方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //将我们写好的类的对象传入到这个方法中即可
        auth.userDetailsService(userDetailsService);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()//关闭防跨域攻击功能
            .authorizeRequests() //对下面请求进行授权
            .antMatchers(
                    //"/index_student.html",
                    "/img/*",
                    "/js/*",
                    "/css/*",
                    "/bower_components/**",
                    "/login.html",
                    "/register.html",
                    "/register"
            ).permitAll() // 允许不登录就能访问
            .anyRequest() //其它请求
            .authenticated() //需要登录才能访问
            .and().formLogin()//使用默认表单进行登录
            .loginPage("/login.html")//设置登录页路径
            .loginProcessingUrl("/login")//设置处理登录的Url
            .failureUrl("/login.html?error")//登录失败跳转的路径
            .defaultSuccessUrl("/index_student.html")//登录成功页
            .and().logout()//开始设置登出
            .logoutUrl("/logout")//设置登出路径
            .logoutSuccessUrl("/login.html?logout");//登出后显示的页面

    }
}







